document.getElementById('exportBtn').addEventListener('click', async () => {
  const statusDiv = document.getElementById('status');
  statusDiv.textContent = '正在获取链接...';

  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    const results = await chrome.scripting.executeScript({
      target: { tabId: tab.id },
      function: scrapeLinks
    });

    const links = results[0].result;
    
    if (links.length === 0) {
      statusDiv.textContent = '未找到任何链接';
      return;
    }

    // 创建CSV内容
    const csvContent = [
      ['标题', '链接', '作者', '点赞数', '图片链接'],
      ...links.map(link => [
        link.title,
        link.url,
        link.author,
        link.likes,
        link.imageUrl
      ])
    ].map(row => row.map(cell => `"${cell}"`).join(',')).join('\n');

    // 创建Blob对象
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8' });
    
    // 下载文件
    const url = URL.createObjectURL(blob);
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    await chrome.downloads.download({
      url: url,
      filename: `小红书笔记链接_${timestamp}.csv`
    });

    statusDiv.textContent = `成功导出 ${links.length} 个链接`;
  } catch (error) {
    statusDiv.textContent = '导出失败：' + error.message;
  }
});

function scrapeLinks() {
  const links = [];
  const noteElements = document.querySelectorAll('div[data-v-a264b01a]');

  noteElements.forEach(note => {
    const titleElement = note.querySelector('.title span');
    const authorElement = note.querySelector('.author .name');
    const likesElement = note.querySelector('.like-wrapper .count');
    const linkElement = note.querySelector('a.cover');
    const imageElement = note.querySelector('img[data-xhs-img]');

    if (titleElement && linkElement) {
      links.push({
        title: titleElement.textContent.trim(),
        url: 'https://www.xiaohongshu.com' + linkElement.getAttribute('href'),
        author: authorElement ? authorElement.textContent.trim() : '未知作者',
        likes: likesElement ? likesElement.textContent.trim() : '0',
        imageUrl: imageElement ? imageElement.getAttribute('src') : ''
      });
    }
  });

  return links;
} 